<template>
	<view class="container">
		<!-- 状态栏 -->
		<view class="status-bar"></view>
		
		
		
		
		
		<!-- 维修单列表 -->
		<view style="padding: 12px 16px; background-color: #f5f5f5;">
			<view 
				v-for="(order, index) in workOrders" 
				:key="index"
				style="background: white; border-radius: 8px; padding: 16px; margin-bottom: 12px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);"
				@click="() => viewOrderDetail(order.rptNo, order.workNo)"
			>
				<view style="display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 12px; padding-bottom: 12px; border-bottom: 1px solid #f0f0f0;">
					<view style="flex: 1;">
						<text style="display: block; font-size: 14px; font-weight: bold; color: #333; margin-bottom: 4px;">报修单号: {{ order.rptNo || '无编号' }}</text>
						<text style="display: block; font-size: 12px; color: #666;">维修单号: {{ order.workNo || '无编号' }}</text>
					</view>
					<view style="padding: 4px 12px; border-radius: 12px; font-size: 12px; background-color: #fff3e0; color: #ff9800;">
						<text>{{ getStatusText(order.statusCode) }}</text>
					</view>
				</view>
				
				<view style="display: flex; justify-content: space-between; font-size: 14px; color: #666; margin-bottom: 8px;">
					<text style="font-weight: 500;">资产编号</text>
					<text style="color: #333;">{{ order.assetCode || '暂无数据' }}</text>
				</view>
				
				<view style="display: flex; justify-content: space-between; font-size: 14px; color: #666; margin-bottom: 8px;">
					<text style="font-weight: 500;">资产名称</text>
					<text style="color: #333;">{{ order.assetName || '暂无数据' }}</text>
				</view>
				
				<view style="display: flex; justify-content: space-between; font-size: 14px; color: #666; margin-bottom: 8px;">
					<text style="font-weight: 500;">故障描述</text>
					<text style="color: #333; flex: 1; text-align: right;">{{ order.faultDescription || '暂无数据' }}</text>
				</view>
				
				<view style="display: flex; gap: 8px; margin-top: 12px;">
					<!-- 如果是待分配状态，显示接取按钮 -->
					<button
						v-if="canTakeOrder(order)"
						style="flex: 1; height: 36px; font-size: 14px; border-radius: 6px; border: none; background-color: #67c23a; color: white;"
						@click.stop="() => takeOrder(order)"
					>
						接取任务
					</button>

					<!-- 如果是已分配给自己，显示查看详情按钮 -->
					<button
						v-else
						style="flex: 1; height: 36px; font-size: 14px; border-radius: 6px; border: none; background-color: #409eff; color: white;"
						@click.stop="() => viewOrderDetail(order.rptNo, order.workNo)"
					>
						查看详情
					</button>
				</view>
			</view>
		</view>
		
		
		<!-- 空状态 -->
		<view class="empty-state" v-if="!loading && workOrdersLength === 0">
			<text class="empty-icon">📋</text>
			<text class="empty-text">暂无维修记录</text>
		</view>
		
		<!-- 加载状态 -->
		<view class="loading-state" v-if="loading">
			<text class="loading-text">加载中...</text>
		</view>
		
		<!-- 更多操作弹窗 -->
		<view class="action-modal" v-if="showActionModal" @click="hideActionModal">
			<view class="modal-content" @click.stop>
				<view class="modal-item" @click="handlePendingMaterial">
					<text class="modal-text">待料</text>
				</view>
				<view class="modal-item" @click="handleAddWork">
					<text class="modal-text">追加工</text>
				</view>
				<view class="modal-item" @click="handlePendingConfirm">
					<text class="modal-text">待确认</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import { listWorkOrder, getWorkOrder, updateWorkOrder, delWorkOrder } from '@/api/repair/workOrder'
import { getFaultReport } from '@/api/repair/faultReport'
import { getUserInfo } from '@/utils/auth'
import permissionManager from '@/utils/permission'

export default {
	data() {
		return {
			loading: false,
			workOrders: [],
			workOrdersLength: 0,
			total: 0,
			currentPage: 1,
			pageSize: 10,
			showActionModal: false,
			currentOrder: {},
			
			// 搜索表单
			searchForm: {
				assetName: '',
				status: ''
			},
			
			// 状态标签
			statusTabs: [
				{ value: '', label: '所有状态' },
				{ value: 'PENDING_REPAIR', label: '待修理' },
				{ value: 'IN_PROGRESS', label: '修理中' },
				{ value: 'COMPLETED', label: '已完成' },
				{ value: 'PENDING_ACKNOWLEDGE', label: '待承认' },
				{ value: 'PENDING_CONFIRM', label: '待确认' }
			],
			currentStatusIndex: 0,
			
		}
	},
	
	computed: {
		workOrdersCount() {
			return this.workOrders ? this.workOrders.length : 0
		}
	},
	
	onLoad() {
		console.log('维修记录页面onLoad')
		console.log('初始workOrders:', this.workOrders)
	},
	
	onShow() {
		console.log('维修记录页面onShow')
		console.log('onShow时workOrders:', this.workOrders)
		
		// 监听刷新事件
		uni.$on('refreshRepairList', () => {
			console.log('收到刷新维修列表事件')
			this.loadWorkOrders()
		})
	},
	
	onReady() {
		console.log('维修记录页面onReady')
		console.log('onReady时workOrders:', this.workOrders)
		// 直接加载真实数据
		this.loadWorkOrders()
	},
	
	onUnload() {
		// 清理事件监听
		uni.$off('refreshRepairList')
	},
	
	methods: {
		
		goBack() {
			uni.navigateBack()
		},
		
		// 加载维修单列表
		async loadWorkOrders() {
			try {
				this.loading = true

				// 获取用户信息进行权限校验
				const userInfo = getUserInfo()
				console.log('当前用户信息:', userInfo)

				// 根据用户角色构建查询参数
				const params = {
					pageNum: this.currentPage,
					pageSize: this.pageSize,
					...this.searchForm
				}

				// 如果是维修人员，只能看到分配给自己的任务
				if (permissionManager.isMaintenanceWorker() && userInfo?.user?.userId) {
					params.assigneeId = userInfo.user.userId
					// 只显示分配给自己的任务（排除待分配状态）
					params.status = 'ASSIGNED,PENDING_EXEC,IN_PROGRESS,WAITING_MATERIAL,PENDING_CONFIRM,COMPLETED,DONE'
				} else if (userInfo?.user?.userId) {
					// 管理员或其他角色，可以选择是否按分配人过滤
					params.assigneeId = userInfo.user.userId
				}


				// 直接调用API加载真实数据
				const res = await listWorkOrder(params)
				
				if (res && res.code === 200) {
					// 获取维修单数据
					const workOrders = res.rows || []
					
					// 为每个维修单获取报修单详情来补充资产信息
					for (let i = 0; i < workOrders.length; i++) {
						const order = workOrders[i]
						
						if (order.rptNo) {
							try {
								// 调用获取报修单详情的API
								const reportRes = await this.getFaultReportDetail(order.rptNo)
								
								// 处理响应格式
								let report = null
								if (reportRes && reportRes.code === 200) {
									report = reportRes.data
								} else if (reportRes && reportRes.data) {
									report = reportRes.data
								}
								
								if (report) {
									// 补充资产信息（尝试多种可能的字段名）
									order.assetCode = report.assetNo || report.asset_no || '暂无数据'
									order.assetName = report.assetName || report.asset_name || '暂无数据'
									order.faultDescription = report.faultDescription || report.fault_description || '暂无数据'
									order.location = report.location || '暂无数据'
									order.deptName = report.deptName || '暂无数据'
								} else {
									// 设置默认值，避免一直显示"加载中..."
									order.assetCode = '暂无数据'
									order.assetName = '暂无数据'
									order.faultDescription = '暂无数据'
								}
								
								// 确保数据更新到响应式系统
								this.$set(this.workOrders, i, order)
							} catch (error) {
								console.log('获取报修单详情失败:', error)
							}
						}
					}
					
					// 如果是维修人员，在前端再次过滤掉待分配状态的任务
					let filteredWorkOrders = workOrders
					if (permissionManager.isMaintenanceWorker() && userInfo?.user?.userId) {
						filteredWorkOrders = workOrders.filter(order => {
							const status = order.statusCode || order.status
							return status !== 'PENDING_ASSIGN'
						})
						console.log('前端过滤前数据量:', workOrders.length, '过滤后数据量:', filteredWorkOrders.length)
					}

					// 使用Vue.set确保响应式更新
					this.$set(this, 'workOrders', filteredWorkOrders)
					this.workOrdersLength = filteredWorkOrders.length
					this.total = res.total || 0
					console.log('补充资产信息后的数据:', this.workOrders)
					
					// 使用nextTick确保DOM更新
					this.$nextTick(() => {
						this.$forceUpdate()
					})
					
				} else {
					// API返回错误，显示空数据
					this.$set(this, 'workOrders', [])
					this.workOrdersLength = 0
					this.total = 0
					console.log('API返回错误:', res.msg || '未知错误')
					
					uni.showToast({
						title: res.msg || '加载失败',
						icon: 'none'
					})
				}
				
			} catch (error) {
				console.error('加载维修单失败:', error)
				this.$set(this, 'workOrders', [])
				this.workOrdersLength = 0
				this.total = 0
				uni.showToast({
					title: '网络错误，请检查网络连接',
					icon: 'none'
				})
			} finally {
				this.loading = false
			}
		},
		
		// 选择状态
		selectStatus(index) {
			this.currentStatusIndex = index
			this.searchForm.status = this.statusTabs[index].value
			this.loadWorkOrders()
		},
		
		// 显示筛选
		showFilter() {
			uni.showToast({
				title: '筛选功能',
				icon: 'none'
			})
		},
		
		// 显示更多操作
		showMoreActions(order) {
			this.currentOrder = order
			this.showActionModal = true
		},
		
		// 通过索引显示更多操作
		showMoreActionsByIndex(index) {
			const order = this.workOrders[index]
			if (order) {
				this.currentOrder = order
				this.showActionModal = true
			}
		},
		
		// 隐藏操作弹窗
		hideActionModal() {
			this.showActionModal = false
		},
		
		// 待料
		handlePendingMaterial() {
			this.hideActionModal()
			uni.showToast({
				title: '已设置为待料',
				icon: 'success'
			})
		},
		
		// 追加工
		handleAddWork() {
			this.hideActionModal()
			uni.showToast({
				title: '已添加追加工',
				icon: 'success'
			})
		},
		
		// 待确认
		handlePendingConfirm() {
			this.hideActionModal()
			uni.showToast({
				title: '已设置为待确认',
				icon: 'success'
			})
		},
		
		
        // 预加载维修单状态字典
        async loadWorkOrderStatusDict() {
            try {
                const res = await uni.request({
                    url: 'http://127.0.0.1:8081/system/status/work-order/list',
                    method: 'GET',
                    header: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${uni.getStorageSync('token')}`
                    },
                    data: { pageNum: 1, pageSize: 9999, enabled: 1 }
                });
                const list = (res.data && (res.data.rows || res.data.data)) || [];
                this._workStatusMap = {};
                list.forEach(it => { if (it && it.code) this._workStatusMap[it.code] = it.name; });
            } catch (e) {
                this._workStatusMap = {};
            }
        },
        // 同步获取状态文本
        getStatusText(status) {
            if (this._workStatusMap && this._workStatusMap[status]) return this._workStatusMap[status];
            return this.getFallbackStatusText(status);
        },
		
		// 兜底状态文本
		getFallbackStatusText(status) {
			const statusMap = {
				'PENDING_ASSIGN': '待分配',
				'ASSIGNED': '待接取',
				'PENDING_EXEC': '待维修',
				'IN_PROGRESS': '维修中',
				'IN_REPAIR': '维修中',
				'WAITING_MATERIAL': '待料中',
				'EXTRA_PROCESSING': '追加工中',
				'COMPLETED': '已完成',
				'DONE': '已完成',
				'PENDING_ACKNOWLEDGE': '待承认',
				'PENDING_CONFIRM': '待确认',
				'CONFIRMED': '已确认',
				'REJECTED': '拒绝确认',
				'ACKNOWLEDGED': '已承认'
			}
			return statusMap[status] || status || '未知状态'
		},
		
		// 获取状态样式类
		getStatusClass(status) {
			const classMap = {
				'PENDING_ASSIGN': 'status-warning',
				'ASSIGNED': 'status-warning', // 待接取状态使用相同的警告色
				'PENDING_EXEC': 'status-danger',
				'IN_PROGRESS': 'status-primary',
				'IN_REPAIR': 'status-primary',
				'WAITING_MATERIAL': 'status-warning',
				'EXTRA_PROCESSING': 'status-warning',
				'COMPLETED': 'status-success',
				'DONE': 'status-success',
				'PENDING_ACKNOWLEDGE': 'status-warning',
				'PENDING_CONFIRM': 'status-warning',
				'CONFIRMED': 'status-success',
				'REJECTED': 'status-danger',
				'ACKNOWLEDGED': 'status-success'
			}
			return classMap[status] || 'status-info'
		},
		
		// 获取状态样式
		getStatusStyle(status) {
			const styleMap = {
				'PENDING_ASSIGN': 'background-color: #fff3e0; color: #ff9800;',
				'ASSIGNED': 'background-color: #fff3e0; color: #ff9800;', // 待接取状态使用相同的警告色
				'PENDING_EXEC': 'background-color: #ffebee; color: #f44336;',
				'IN_PROGRESS': 'background-color: #e8f5e8; color: #4caf50;',
				'IN_REPAIR': 'background-color: #e8f5e8; color: #4caf50;',
				'WAITING_MATERIAL': 'background-color: #fff3e0; color: #ff9800;',
				'EXTRA_PROCESSING': 'background-color: #fff3e0; color: #ff9800;',
				'COMPLETED': 'background-color: #f3e5f5; color: #9c27b0;',
				'DONE': 'background-color: #f3e5f5; color: #9c27b0;',
				'PENDING_ACKNOWLEDGE': 'background-color: #fff8e1; color: #ff9800;',
				'PENDING_CONFIRM': 'background-color: #fce4ec; color: #e91e63;',
				'CONFIRMED': 'background-color: #e8f5e8; color: #4caf50;',
				'REJECTED': 'background-color: #ffebee; color: #f44336;',
				'ACKNOWLEDGED': 'background-color: #e8f5e8; color: #4caf50;'
			}
			return styleMap[status] || 'background-color: #f5f5f5; color: #999;'
		},
		
		// 获取报修单详情
		async getFaultReportDetail(reportNo) {
			try {
				console.log(`调用getFaultReport API，参数: ${reportNo}`)
				// 使用标准的API函数
				const res = await getFaultReport(reportNo)
				console.log('报修单详情响应:', res)
				console.log('响应结构:', {
					code: res?.code,
					message: res?.msg,
					hasData: !!res?.data,
					dataType: typeof res?.data,
					dataKeys: res?.data ? Object.keys(res.data) : 'null'
				})
				return res
			} catch (error) {
				console.error('获取报修单详情失败:', error)
				return null
			}
		},
		
		// 判断是否可以接取任务
		canTakeOrder(order) {
			// 必须是维修人员
			if (!permissionManager.isMaintenanceWorker()) {
				return false
			}

			// 只有待接取状态（ASSIGNED）的任务才能接取
			return order.statusCode === 'ASSIGNED' || order.status === 'ASSIGNED'
		},

		// 接取任务
		async takeOrder(order) {
			try {
				console.log('开始接取任务:', order.workNo);

				// 获取当前用户信息
				const userInfo = getUserInfo()
				if (!userInfo?.user?.userId) {
					uni.showToast({
						title: '用户信息获取失败',
						icon: 'none'
					})
					return
				}

				// 调用接取任务API - 需要先获取完整的维修单数据
				const workOrderRes = await getWorkOrder(order.workNo)
				let res = null
				
				if (workOrderRes && workOrderRes.code === 200) {
					const workOrderData = workOrderRes.data

					// 只更新必要的字段，避免覆盖其他重要数据
					workOrderData.assigneeId = userInfo.user.userId
					workOrderData.statusCode = 'PENDING_EXEC'  // 接取后状态变为待执行
					workOrderData.assigneeName = userInfo.user.nickName || userInfo.user.userName

					res = await updateWorkOrder(workOrderData)
				} else {
					throw new Error('获取维修单详情失败')
				}

				console.log('接取任务完成，结果:', res?.code === 200 ? '成功' : '失败')

				if (res && res.code === 200) {
					uni.showToast({
						title: '任务接取成功',
						icon: 'success'
					})

					// 立即更新本地任务状态
					const targetOrder = this.workOrders.find(item => item.workNo === order.workNo)
					if (targetOrder) {
						targetOrder.statusCode = 'PENDING_EXEC'
						targetOrder.status = 'PENDING_EXEC'
						targetOrder.assigneeId = userInfo.user.userId
						targetOrder.assigneeName = userInfo.user.nickName || userInfo.user.userName
					}

					// 重新加载任务列表以确保数据一致性
					this.loadWorkOrders()
				} else {
					uni.showToast({
						title: res?.msg || '接取任务失败',
						icon: 'none'
					})
				}
			} catch (error) {
				console.error('接取任务失败:', error)
				uni.showToast({
					title: '接取任务失败',
					icon: 'none'
				})
			}
		},

		// 查看维修单详情
		viewOrderDetail(rptNo, workNo) {
			console.log('点击查看维修单，报修单号:', rptNo, '维修单号:', workNo)

			// 根据rptNo和workNo从workOrders中查找完整的order对象
			const order = this.workOrders.find(item => {
				return String(item.rptNo || '') === String(rptNo || '') &&
					   String(item.workNo || '') === String(workNo || '')
			})

			// 检查参数
			if (!order || !order.rptNo) {
				console.error('维修单数据为空或缺少报修单号')
				console.log('传入的rptNo:', rptNo, 'workNo:', workNo)
				console.log('当前workOrders长度:', this.workOrders.length)
				console.log('workOrders数据:', this.workOrders)
				uni.showToast({
					title: '数据错误',
					icon: 'none'
				})
				return
			}
			
			// 跳转到报修单详情页面（通过报修单号）
			uni.navigateTo({
				url: `/pages/repair/detail?reportNo=${order.rptNo}&workNo=${order.workNo || ''}`,
				success: () => {
					console.log('跳转到报修单详情页面成功')
				},
				fail: (error) => {
					console.error('跳转失败:', error)
					uni.showToast({
						title: '跳转失败',
						icon: 'none'
					})
				}
			})
		}
	}
}
</script>

<style scoped>
.container {
	display: flex;
	flex-direction: column;
	min-height: 100vh;
	background-color: #f5f5f5;
}

.status-bar {
	height: 44px;
	background-color: white;
}

.header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 12px 16px;
	background-color: white;
	border-bottom: 1px solid #e0e0e0;
}

.header-left {
	display: flex;
	align-items: center;
}

.back-icon {
	font-size: 18px;
	color: #333;
}

.header-title {
	font-size: 18px;
	font-weight: bold;
	color: #333;
}

.header-right {
	width: 20px;
}

.search-section {
	padding: 12px 16px;
	background-color: white;
	border-bottom: 1px solid #e0e0e0;
}

.search-bar {
	display: flex;
	align-items: center;
	gap: 12px;
}

.search-input-wrapper {
	flex: 1;
	display: flex;
	align-items: center;
	background-color: #f5f5f5;
	border-radius: 20px;
	padding: 8px 12px;
}

.search-icon {
	font-size: 16px;
	color: #999;
	margin-right: 8px;
}

.search-input {
	flex: 1;
	font-size: 14px;
	color: #333;
}

.filter-icon {
	width: 32px;
	height: 32px;
	display: flex;
	align-items: center;
	justify-content: center;
	background-color: #f5f5f5;
	border-radius: 16px;
}

.status-tabs {
	background-color: white;
	border-bottom: 1px solid #e0e0e0;
}

.tabs-scroll {
	white-space: nowrap;
}

.tabs-container {
	display: flex;
	padding: 0 16px;
}

.tab-item {
	padding: 12px 16px;
	margin-right: 8px;
	position: relative;
}

.tab-item.active::after {
	content: '';
	position: absolute;
	bottom: 0;
	left: 0;
	right: 0;
	height: 2px;
	background-color: #4a94ff;
}

.tab-text {
	font-size: 14px;
	color: #666;
	white-space: nowrap;
}

.tab-item.active .tab-text {
	color: #4a94ff;
	font-weight: bold;
}

.records-list {
	padding: 12px 16px;
}

.record-card {
	background-color: white;
	border-radius: 8px;
	margin-bottom: 12px;
	padding: 16px;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.card-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 12px;
}

.order-number {
	font-size: 16px;
	font-weight: bold;
	color: #333;
}

.status-badge {
	padding: 4px 8px;
	border-radius: 12px;
	font-size: 12px;
	font-weight: bold;
}

.status-pending {
	background-color: #ffebee;
	color: #f44336;
}

.status-progress {
	background-color: #e3f2fd;
	color: #2196f3;
}

.status-completed {
	background-color: #f3e5f5;
	color: #9c27b0;
}

.status-acknowledge {
	background-color: #fff3e0;
	color: #ff9800;
}

.status-confirm {
	background-color: #e8f5e8;
	color: #4caf50;
}

.card-content {
	margin-bottom: 12px;
}

.info-row {
	display: flex;
	margin-bottom: 8px;
}

.info-label {
	font-size: 14px;
	color: #666;
	margin-right: 8px;
	min-width: 80px;
}

.info-value {
	font-size: 14px;
	color: #333;
	flex: 1;
}

.card-actions {
	display: flex;
	justify-content: flex-end;
}

.action-overlay {
	background-color: #f5f5f5;
	padding: 6px 12px;
	border-radius: 4px;
}

.more-text {
	font-size: 12px;
	color: #666;
}

.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 60px 20px;
}

.empty-icon {
	font-size: 48px;
	margin-bottom: 16px;
}

.empty-text {
	font-size: 16px;
	color: #999;
}

.loading-state {
	display: flex;
	justify-content: center;
	padding: 20px;
}

.loading-text {
	font-size: 14px;
	color: #666;
}

.action-modal {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(0, 0, 0, 0.5);
	display: flex;
	justify-content: center;
	align-items: center;
	z-index: 1000;
}

.modal-content {
	background-color: white;
	border-radius: 8px;
	overflow: hidden;
	min-width: 200px;
}

.modal-item {
	padding: 16px 20px;
	border-bottom: 1px solid #e0e0e0;
}

.modal-item:last-child {
	border-bottom: none;
}

.modal-text {
	font-size: 16px;
	color: #333;
}

</style>